package com.wangyf.thread.c_021_question;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * 写一个题目: 一个线程添加10个元素到容器 另一个线程监听容器 到5个的时候打印后停止
 * Created by feng on 2021/1/16.
 * 使用 CountDownLatch实现
 */
public class T04_CountDownLatch {

    public static void main(String[] args) throws InterruptedException {
        List<Object> list = new ArrayList<>();
        CountDownLatch latch = new CountDownLatch(1);


        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                list.add(new Object());
                System.out.println(list.size());
                if (list.size() == 5) {
                    latch.countDown();
                }
            }
        });
        Thread t2 = new Thread(() -> {
            System.out.println("t2 begin");
            if (list.size() != 5) {
                try {
                    latch.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("t2 end");
            }
        });

        t2.start();
        Thread.sleep(100);// 确保 t2 先执行 await
        t1.start();

    }
}
